import * as vscode from 'vscode';
import * as auth from './auth';
import * as snooping from './snooping';
import * as followings from './followings';
import { FollowsItem } from './followings';


export async function activate(context: vscode.ExtensionContext) {
  console.log('Activating VSCDD...');

  //context.subscriptions.push(
  //  vscode.commands.registerCommand('vscdd.test', async () => {
  //    await updateConfiguration('vscdd.dummy', {aaa: Date()});
  //  })
  //)

  /* 摸鱼监控 */
  /** 自启动 */
  const snooping_startup: 'off' | 'all' | 'special' =
      vscode.workspace.getConfiguration('vscdd.snooping').get('enableOnStartup')!;
  if (snooping_startup !== 'off') {
    const follows = vscode.workspace.getConfiguration('vscdd').get('follows') as FollowsItem[];
    let snoop_uids: number[] = [];
    switch (snooping_startup) {
    case 'special':
      for (let f of follows) {
        if (typeof f.special !== 'undefined' && f.special)
          snoop_uids.push(f.uid);
      }
      break;
    case 'all':
      for (let f of follows)
        snoop_uids.push(f.uid);
      break;
    }
    snooping.startMonitoring(snoop_uids, true);
  }
  /** commands */
  context.subscriptions.push(
    vscode.commands.registerCommand('vscdd.startMonitoring', snooping.startMonitoring),
    vscode.commands.registerCommand('vscdd.stopMonitoring', snooping.stopMonitoring)
  );

  /* 登录 */
  /** 登录状态检查 */
  auth.initAuth();
  /** commands */
  context.subscriptions.push(
    vscode.commands.registerCommand('vscdd.initAuth', async () => await auth.initAuth(true))
  );

  /* 关注列表 */
  context.subscriptions.push(
    vscode.commands.registerCommand('vscdd.refreshFollowsConfig', followings.updateFollows),
    vscode.commands.registerCommand('vscdd.pullFollowingList', async () => {
      let merge_mode: vscode.QuickPickItem & {key: string} | undefined = undefined;
      merge_mode = await vscode.window.showQuickPick(
          [ {key: 'skip', label: '跳过', picked: true},
            {key: 'truncate', label: '清空本地配置，重新做人'},
            {key: 'overwrite', label: '覆写本地配置'} ],
          {canPickMany: false, placeHolder: '请选择合并行为'});
      if (typeof merge_mode === 'undefined')
        return;
      // just to make TypeScript happy :)
      switch (merge_mode.key) {
        case 'skip': case 'truncate': case 'overwrite': break;
        default: return;
      }
      let choices = await vscode.window.showQuickPick(
          [ { key: 'only_vup', label: '只拉取虚拟主播', picked: true,
              description: '通过当前直播间分区是否为“虚拟主播”判断' },
            { key: 'sign_as_hint', label: '签名合并至额外描述', picked: true,
              description: '用作模糊查询 hint' },
            { key: 'skip_non_livers', label: '跳过非主播', picked: true } ],
          {canPickMany: true});
      if (typeof choices === 'undefined')
        return;
      let chosen_set = new Map<string, undefined>();
      for (let c of choices)
        chosen_set.set(c.key, undefined);
      try {
        await followings.mergeFollowsFromSite({
          only_vup: chosen_set.has('only_vup'),
          sign_as_hint: chosen_set.has('sign_as_hint'),
          skip_non_livers: chosen_set.has('skip_non_livers'),
          merge_mode: merge_mode.key
        });
      }
      catch (e) {
        console.debug(e);
        vscode.window.showErrorMessage('请求异常：可能是叔叔盯上你了，过一分钟再来！');
      }
    })
  );

  if (false) {
  context.subscriptions.push(
    vscode.commands.registerCommand('vscdd.openLiveRoom', async () => {
      let room_id: number = 21741192;
      try {
        const view = vscode.window.createWebviewPanel(
          'vscddLiveRoom',
          `VSCDD - ${room_id}`,
          { preserveFocus: true, viewColumn: vscode.ViewColumn.One },
          { enableScripts: true }
        )
        let img_uri = vscode.Uri.file('assets/210402112239.jpg');
        view.webview.html = `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
test
<img src="${view.webview.asWebviewUri(img_uri)}" />
</body>
</html>`;
      } catch (e) {
        console.warn(e);
      }
    })
  );
  }
}

// this method is called when your extension is deactivated
export function deactivate() {
  snooping.tearDownSnooping();
}
